//
//  ShopCarViewModel.m
//  GLGW_Shoping
//
//  Created by yang on 2018/11/19.
//  Copyright © 2018年 yang. All rights reserved.
//

#import "ShopCarViewModel.h"
#import "StoreGoodsTableViewCell.h"
#import "GoodsTypeTableViewHeaderFooterView.h"
#import "NoDataFootTableViewHeaderFooterView.h"
#import "ShopCarBootomView.h"
#import "ShopCarSeverHeaderView.h"
#import "ShopCarModel.h"

@interface ShopCarViewModel ()<UITableViewDelegate,UITableViewDataSource>{
    UITableView * self_tableView;
    UIView * selfView;
    ShopCarSeverHeaderView * shopCarHeaderView;
    //标记
    NSInteger jiSuMark;
    NSInteger puTongMark;
    NSInteger queHuoMark;
    //
    CGFloat tableViewHeight;//初始化tableView的高度
    ShopCarBootomView * bottomView;
}
@property(nonatomic,strong) ShopCarModel_Header * headerBool;
@property(nonatomic,strong) NSMutableArray<ShopCarModel_Data *> * jiSuArr;//极速
@property(nonatomic,strong) NSMutableArray<ShopCarModel_Data *> * puTongArr;//普通
@property(nonatomic,strong) NSMutableArray<ShopCarModel_Data *> * queHuoArr;//缺货

@property(nonatomic,strong) NSMutableArray * sectionDataArr;//section

@property(nonatomic,strong)ShopCarModel * shop_CarModel;
@property(nonatomic,strong) NSMutableArray * selectGoodsArr;//选择的商品
@end

@implementation ShopCarViewModel

-(instancetype)initWithViewToViewModel:(UITableView *)tableView theSuperView:(UIView *)superView{
    if (self = [super initWithViewToViewModel:tableView theSuperView:superView]) {
        selfView = superView;
        self.jiSuArr = [NSMutableArray arrayWithCapacity:0];
        self.puTongArr = [NSMutableArray arrayWithCapacity:0];
        self.queHuoArr = [NSMutableArray arrayWithCapacity:0];
        self.sectionDataArr = [NSMutableArray arrayWithCapacity:0];
        self.headerBool = [ShopCarModel_Header new];
        self.selectGoodsArr = [NSMutableArray arrayWithCapacity:0];
        tableViewHeight= tableView.height;
        tableView.height = tableViewHeight - kHeightProportion_In_iPhoneTriploid(68);
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.mj_footer.hidden = YES;
        [tableView registerClass:[GoodsTypeTableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"GoodsTypeTableViewHeaderFooterView"];
        [tableView registerClass:[NoDataFootTableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"NoDataFooterView"];
        if (self.accountType == AccountType_FreeManagers) {
            tableView.tableHeaderView = [self createHeaderView];
        }
        [superView addSubview:tableView];
        self_tableView = tableView
        ;        //
        bottomView = [[ShopCarBootomView alloc] initWithFrame:CGRectMake(0, kY_With_View(tableView, 0), KScreenWidth, kHeightProportion_In_iPhoneTriploid(68)) inSuperView:superView];
        kWeakSelf(self);
        bottomView.Block_AllSelectAction = ^(GLGWButton * _Nonnull allBut) {
            if (weakself.sectionDataArr.count == 0) {
                return;
            }
            allBut.selected = !allBut.selected;
            for (ShopCarModel_Header * headerDataModel in weakself.sectionDataArr) {
                if (weakself.editBool) {
                    headerDataModel.sectionBool = allBut.selected;
                    for (ShopCarModel_Data * dataModel in headerDataModel.dataSourceArr) {
                        dataModel.isSelectBool = allBut.selected;
                    }
                }else{
                    if (![headerDataModel.titleImageStr isEqualToString:@"icon_quehuo"]) {
                        headerDataModel.sectionBool = allBut.selected;
                        for (ShopCarModel_Data * dataModel in headerDataModel.dataSourceArr) {
                            dataModel.isSelectBool = allBut.selected;
                        }
                    }
                }
            }
            [weakself allSelectAdd];
            [tableView reloadData];
        };
        //
        bottomView.Block_JieBottom = ^{
            if (!weakself.editBool) {
                if (self.selectGoodsArr.count== 0) {
                    [GLGWProgressHUD showNotice:@"请选择商品" view:nil];
                    return;
                }
                if (weakself.delegate && [weakself.delegate respondsToSelector:@selector(selectJieSuang:)]) {
                    [weakself.delegate selectJieSuang:weakself.selectGoodsArr];
                }
            }else{//删除
                [weakself delegateGoods];
            }
        };
    }
    return self;
}

-(UIView *)createHeaderView{
    shopCarHeaderView = [[ShopCarSeverHeaderView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, kHeightProportion_In_iPhoneTriploid(54))];
    shopCarHeaderView.height = kHeightProportion_In_iPhoneTriploid(104);
    return shopCarHeaderView;
}

#pragma mark -- set
-(void)setEditBool:(BOOL)editBool{
    _editBool = editBool;
    if (_editBool) {
        [UIView animateWithDuration:0.25 animations:^{
            self->self_tableView.height = self->tableViewHeight - kHeightProportion_In_iPhoneTriploid(49);
            self->bottomView.frame = CGRectMake(0, kY_With_View(self->self_tableView, 0), KScreenWidth, kHeightProportion_In_iPhoneTriploid(49));
        }];
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            self->self_tableView.height = self->tableViewHeight - kHeightProportion_In_iPhoneTriploid(68);
            self->bottomView.frame = CGRectMake(0, kY_With_View(self->self_tableView, 0), KScreenWidth, kHeightProportion_In_iPhoneTriploid(68));
        }];
    }
    bottomView.editIsBool = _editBool;
    [self.selectGoodsArr removeAllObjects];
    for (ShopCarModel_Header * headerDataModel in self.sectionDataArr) {
        headerDataModel.sectionBool = NO;
        for (ShopCarModel_Data * dataModel in headerDataModel.dataSourceArr) {
            dataModel.isSelectBool = NO;
        }
    }
    [self_tableView reloadData];
    bottomView.allGoodsBool = NO;
    //
    if (self.editBool) {
        return;
    }
    if (self.selectGoodsArr.count>0) {
        bottomView.payBut.title = [NSString stringWithFormat:@"去结算(%ld)",self.selectGoodsArr.count];
    }else{
        bottomView.payBut.title = @"去结算";
    }
}
#pragma mark -- 数据请求
-(void)shopCarRequestData{
    [self.queHuoArr removeAllObjects];
    [self.puTongArr removeAllObjects];
    [self.jiSuArr removeAllObjects];
    [self.sectionDataArr removeAllObjects];
    jiSuMark = 0;
    puTongMark = 0;
    queHuoMark = 0;
    NSDictionary * shopDic = @{@"userId":@"1231232"};
    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kProductInfos] lodingView:nil lodingTextString:@"" isLoding:YES parameters:shopDic success:^(id  _Nullable response) {
        self.shop_CarModel = [ShopCarModel yy_modelWithJSON:response];
        if (self.shop_CarModel.code == 0) {
            //选择好
            for (ShopCarModel_Data * l_Data in self.shop_CarModel.data) {
                if (l_Data.productQuantity == 0) {
                    [self.queHuoArr addObject:l_Data];
                }else{
                    if (l_Data.tradingMode == 1) {
                        [self.puTongArr addObject:l_Data];
                    }else{
                        [self.jiSuArr addObject:l_Data];
                    }
                }
            }
            //排好
            for (ShopCarModel_Data * s_data in self.jiSuArr) {
                if (self->jiSuMark == s_data.shopId) {
                    s_data.isSimilar = NO;
                }else{
                    s_data.isSimilar = YES;
                    self->jiSuMark = s_data.shopId;
                }
            }
            for (ShopCarModel_Data * p_data in self.puTongArr) {
                if (self->puTongMark == p_data.shopId) {
                    p_data.isSimilar = NO;
                }else{
                    p_data.isSimilar = YES;
                    self->puTongMark = p_data.shopId;
                }
            }
            for (ShopCarModel_Data * q_data in self.queHuoArr) {
                if (self->queHuoMark == q_data.shopId) {
                    q_data.isSimilar = NO;
                }else{
                    q_data.isSimilar = YES;
                    self->queHuoMark = q_data.shopId;
                }
            }
            //
            if (self.jiSuArr.count>0) {
                ShopCarModel_Header * jiSuHeader = [ShopCarModel_Header new];
                jiSuHeader.sectionBool = NO;
                jiSuHeader.titleImageStr = @"icon_jisujiaoyi";
                jiSuHeader.titleStr = @" 极速交易商品";
                jiSuHeader.dataSourceArr = self.jiSuArr;
                [self.sectionDataArr addObject:jiSuHeader];
            }
            //
            if (self.puTongArr.count>0) {
                ShopCarModel_Header * puTongHeader = [ShopCarModel_Header new];
                puTongHeader.sectionBool = NO;
                puTongHeader.titleImageStr = @"icon_changqiqiugou";
                puTongHeader.titleStr = @" 普通商品";
                puTongHeader.dataSourceArr = self.puTongArr;
                [self.sectionDataArr addObject:puTongHeader];
            }
            //
            if (self.queHuoArr.count>0) {
                ShopCarModel_Header * queHuoHeader = [ShopCarModel_Header new];
                queHuoHeader.sectionBool = NO;
                queHuoHeader.titleImageStr = @"icon_quehuo";
                queHuoHeader.titleStr = @" 缺货商品";
                queHuoHeader.dataSourceArr = self.queHuoArr;
                [self.sectionDataArr addObject:queHuoHeader];
            }
            [self allSelectAdd];
            [self->self_tableView reloadData];
        }
        [self->self_tableView.mj_footer endRefreshing];
        [self->self_tableView.mj_header endRefreshing];
    } failure:^(NSError * _Nullable error) {
        [self->self_tableView.mj_footer endRefreshing];
        [self->self_tableView.mj_header endRefreshing];
    }];
}
//商品数量改变
-(void)goodsNumAddRequestData:(ShopCarModel_Data *)changeModel theNSIndexPath:(NSIndexPath *)pathIndex theNum:(int)g_num{
    NSDictionary * goodsDic = @{@"id":@(changeModel.goods_id),@"num":@(g_num)};
    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kEditNum] lodingView:nil lodingTextString:@"" isLoding:YES parameters:goodsDic success:^(id  _Nullable response) {
        BaseModel * b_Model = [BaseModel yy_modelWithJSON:response];
        if (b_Model.code == 0) {
            changeModel.num = g_num;
            StoreGoodsTableViewCell * cell_goods = [self->self_tableView cellForRowAtIndexPath:pathIndex];
            cell_goods.shopProductModel = changeModel;
        }
    } failure:^(NSError * _Nullable error) {
        
    }];
}
//删除购物车商品
-(void)delegateGoods{
    if (self.selectGoodsArr.count == 0) {
        [GLGWProgressHUD showNotice:@"请选择商品" view:nil];
        return;
    }
     NSString * id_str;
    int i = 0;
    for (ShopCarModel_Data * shop_Data in self.selectGoodsArr) {
        if (i == 0) {
            id_str = [NSString stringWithFormat:@"%ld",(long)shop_Data.goods_id];
        }else{
            id_str = [NSString stringWithFormat:@"%@,%ld",id_str,(long)shop_Data.goods_id];
        }
        i++;
    }
    NSDictionary * deleDic = @{@"userId":@"1231232",
                               @"ids":koString(id_str)};
    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kDelShoparProduct] lodingView:nil lodingTextString:@"" isLoding:YES parameters:deleDic success:^(id  _Nullable response) {
        BaseModel * b_model = [BaseModel yy_modelWithJSON:response];
        if (b_model.code == 0) {
            [self shopCarRequestData];
        }
    } failure:^(NSError * _Nullable error) {

    }];
}
//计算商品钱数
-(void)allSelectAdd{
    CGFloat allMoney = 0.00;
    [self.selectGoodsArr removeAllObjects];
    for (ShopCarModel_Data * dataModel in self.shop_CarModel.data) {
        if (dataModel.isSelectBool) {
            allMoney = allMoney + dataModel.price*dataModel.num;
            [self.selectGoodsArr addObject:dataModel];
        }
    }
    bottomView.allSelectGoodsMoney = allMoney;
    if (self.editBool) {
        return;
    }
    if (self.selectGoodsArr.count>0) {
        bottomView.payBut.title = [NSString stringWithFormat:@"去结算(%ld)",self.selectGoodsArr.count];
    }else{
        bottomView.payBut.title = @"去结算";
    }
}

-(void)isAllSelect{
    BOOL allSelectBool = YES;
    if (!self.editBool) {
        for (ShopCarModel_Header * headerDataModel in self.sectionDataArr) {
            if (![headerDataModel.titleImageStr isEqualToString:@"icon_quehuo"]) {
                for (ShopCarModel_Data * s_Model in headerDataModel.dataSourceArr) {
                    if (!s_Model.isSelectBool) {
                        allSelectBool = NO;
                    }
                }
            }
        }
    }else{
        for (ShopCarModel_Data * dataModel in self.shop_CarModel.data) {
            if (!dataModel.isSelectBool) {
                allSelectBool = NO;
            }
        }
    }
    bottomView.allGoodsBool = allSelectBool;
}
#pragma mark  ---- UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.sectionDataArr.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    ShopCarModel_Header * headerModel = self.sectionDataArr[section];
    return headerModel.dataSourceArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ShopCarModel_Header * headerModel = self.sectionDataArr[indexPath.section];
    ShopCarModel_Data * dataModel = headerModel.dataSourceArr[indexPath.row];
    StoreGoodsTableViewCell * cell = [StoreGoodsTableViewCell cellWithTableView:tableView];
    cell.shopProductModel = dataModel;
    cell.Block_GoodsNum = ^(int ch_Tag) {
        [self goodsNumAddRequestData:dataModel theNSIndexPath:indexPath theNum:ch_Tag];
    };
    cell.Block_GoodsSelect = ^(GLGWButton * _Nonnull gSelectBut) {
        if ([headerModel.titleImageStr isEqualToString:@"icon_quehuo"] && !self.editBool) {
            return;
        }
        gSelectBut.selected = !gSelectBut.selected;
        dataModel.isSelectBool = gSelectBut.selected;
        [self allSelectAdd];
        headerModel.sectionBool = YES;
        for (ShopCarModel_Data * header_Model in headerModel.dataSourceArr) {
            if (!header_Model.isSelectBool) {
                headerModel.sectionBool = NO;
            }
        }
        [self isAllSelect];
        [tableView reloadData];
    };
    [cell setSepartionLineWith:lineModel_Half];
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    ShopCarModel_Header * hraderModel = self.sectionDataArr[section];
    GoodsTypeTableViewHeaderFooterView * goodsHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"GoodsTypeTableViewHeaderFooterView"];
    goodsHeaderView.h_model = hraderModel;
    goodsHeaderView.Block_HeaderAllSelect = ^(GLGWButton * _Nonnull selectBoolBut) {
        if ([hraderModel.titleImageStr isEqualToString:@"icon_quehuo"] && !self.editBool) {
            return;
        }
        selectBoolBut.selected = !selectBoolBut.selected;
        hraderModel.sectionBool = selectBoolBut.selected;
        for (ShopCarModel_Data * header_Model in hraderModel.dataSourceArr) {
            header_Model.isSelectBool = selectBoolBut.selected;
        }
        [self allSelectAdd];
        [self isAllSelect];
        [tableView reloadData];
    };
//    goodsHeaderView.Block_HeaderAllSelect = ^(BOOL selectBool) {
//        if ([headerModel.titleImageStr isEqualToString:@"icon_quehuo"] && !self.editBool) {
//            return;
//        }
//        sender.selected = !sender.selected;
//        hraderModel.sectionBool = selectBool;
//        for (ShopCarModel_Data * header_Model in hraderModel.dataSourceArr) {
//            header_Model.isSelectBool = selectBool;
//        }
//
//        [self allSelectAdd];
//        [self isAllSelect];
//        [tableView reloadData];
//    };
    return goodsHeaderView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return kHeightProportion_In_iPhoneTriploid(50);;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    NoDataFootTableViewHeaderFooterView * footView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"NoDataFooterView"];
    return footView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

@end
